/* 借助于之前的合并两条有序链表的函数来完成，
  每次传递两条链表进去，当数组为空时则返回我们要的那条链表
*/
function mergeKLists (lists) {
  // write code here
  let nodes = new ListNode(-1)
  let p = mergeTwoList(nodes.next, lists.pop())
  while (lists.length > 0) {
    p = mergeTwoList(p, lists.pop())
  }
  return p
  // return mergeTwoList(lists[0],lists[1])
}
function mergeTwoList (pHead1, pHead2) {
  if (pHead1 === null) return pHead2
  if (pHead2 === null) return pHead1
  const node = new ListNode(-1)
  let pre = node
  while (pHead1 && pHead2) {
    if (pHead1.val <= pHead2.val) {
      pre.next = pHead1
      pHead1 = pHead1.next
    } else {
      pre.next = pHead2
      pHead2 = pHead2.next
    }
    pre = pre.next
  }
  pre.next = pHead1 === null ? pHead2 : pHead1
  return node.next
}